const Behavior = require('@/behaviors/common'); // --混入
import Http from '@/services/api/index';
const Util = require('@/utils/util.js')
const Toast = require('@/utils/toast')
const Storage = require('@/utils/storage')
const appInstance = getApp();
console.log(Http)
const {
  miniProgram: {
    envVersion
  }
} = wx.getAccountInfoSync();
Page({
  behaviors: [Behavior], // 引入Behavior
  startTime: null,
  observer: null,
  data: {
    loading: true,
    bgColor:'#ccc',
    baseUrl: appInstance.globalData.baseUrl,
    searchText: '',
    isObtained: false,
    bannersList: [],
    goodsList: [],
    notice: {},
    categorysList: [],
    // --精选商品 轮播图
    currentIndex: 1,
    featuredsList: []
  },
  onLoad() {
    console.log("Home Load");
    setTimeout(() => {
      this.setData({
        loading: false
      }); // 3秒后隐藏
    }, 2000);
    // 获取当前性能数据
    this.startTime = Date.now()
    // --请求合并
    Promise.all([
      this.fetchBanner(),
      this.fetchNotice(),
      this.fetchCategory(),
      this.fetchFeatureds()
    ]).then(([banner, notices, categorys, featureds]) => {
      console.log(categorys)
      this.setData({
        bannersList: banner.data,
        notice: notices.data[0],
        categorysList: categorys.data,
        featuredsList: featureds.data
      })
    })

    // 创建 IntersectionObserver 实例
    this.observer = wx.createIntersectionObserver(this)

    // 监听目标节点进入视窗
    this.observer.relativeToViewport({})
      .observe('.To-Viewport', (res) => {
        console.log('目标元素可见性变化:', res)
        if (res.intersectionRatio > 0) {
          // 元素进入视图
          console.log('元素进入视图区域')
          if (this.data.isObtained) return;
          // --请求合并
          Promise.all([
            this.fetchBestsellers(),
            this.fetchHotrecommendation()
          ]).then(([bestsellers, products, ]) => {
            this.setData({
              isObtained: true,
              bestsellersList: bestsellers.data,
              goodsList: products.data
            })
          })
        } else {
          // 元素离开视图
          console.log('元素离开视图区域')
        }
      })

    // // 创建 Worker 实例
    // this.worker = wx.createWorker('/workers/compute.worker.js')

    // // 监听 Worker 消息
    // this.worker.onMessage((res) => {
    //   console.log('主线程收到Worker消息:', res)
    //   this.setData({
    //     result: res.data,
    //     loading: false
    //   })
    // })

    // // 监听 Worker 错误
    // this.worker.onError((err) => {
    //   console.error('Worker发生错误:', err)
    //   this.setData({
    //     loading: false
    //   })
    // })
  },
  onShow() {},
  onReady() {
    const firstRenderTime = Date.now() - this.startTime
    console.log("FCP首屏渲染时间：", firstRenderTime)
    // --事件上报
    wx.reportEvent('first_render', {
      duration: firstRenderTime,
      path: this.route
    })
  },
  handleLogin() {},
  goToSearch() {
    wx.navigateTo({
      url: '/pages/search/index'
    })
  },
  toTest: function () {
    wx.navigateTo({
      url: '/pages/canvas/index',
    })
  },

  async fetchBanner() {
    try {
      const banners = await Http.get('/api/home/banner', {}, {
        skipAuth: true
      })
      return banners;
    } catch (err) {
      console.error('加载商品失败', err)
    }
  },
  async fetchNotice() {
    try {
      const notices = await Http.get('/api/home/notice', {}, {
        skipAuth: true
      })
      return notices;
    } catch (err) {
      console.error('加载商品失败', err)
    }
  },
  async fetchCategory() {
    try {
      const categorys = await Http.get('/api/home/category', {}, {
        skipAuth: true
      })
      return categorys;
    } catch (err) {
      console.error('加载商品失败', err)
    }
  },
  async fetchFeatureds() {
    try {
      const featureds = await Http.get('/api/home/featured', {}, {
        skipAuth: true
      })
      return featureds;
    } catch (err) {
      console.error('加载商品失败', err)
    }
  },
  async fetchBestsellers() {
    try {
      const bestsellers = await Http.get('/api/home/bstseller', {}, {
        skipAuth: true
      })
      return bestsellers;
    } catch (err) {
      console.error('加载商品失败', err)
    }
  },
  async fetchHotrecommendation() {
    try {
      const products = await Http.get('/api/home/recommend', {
        page: 1,
        size: 10
      }, {
        skipAuth: true
      })
      return products;
    } catch (err) {
      console.error('加载商品失败', err)
    }
  },
  onUnload() {
    this.observer.disconnect()
  }
})